﻿using System;
using System.Net.Sockets;
using System.Net;
using System.Runtime.Serialization.Formatters.Binary;
using System.Threading;
using System.Windows.Forms;
using ApplLogic.ApplClasses;
using ConnectionObjects;
using TCPClient.RequestsToServerHandlers;
using TCPClient.UI;

namespace TCPClient
{
    public class Client
    {
        private TcpClient m_TCPClient = new TcpClient();
        private IPEndPoint m_ServerEndPoint = null;
        private NetworkStream m_Stream = null;
        private Form m_BaseForm;
        private LoginForm m_LoginForm;

        public Client()
        {
            createConnetionToServer();
            if (m_TCPClient.Connected)
            {
                Console.WriteLine("Successuly connected with server");
                handleLogin();
                
            }
        }

        private void createUI(object sender, EventArgs e)
        {
            LoginEventArgs loginEventArgs = e as LoginEventArgs;
            m_BaseForm = loginEventArgs.LoginType is ApplWorker
                             ? (Form)
                               new WorkerMainForm(new RequestsToServerHandlerForWorker(m_Stream,loginEventArgs.LoginType as ApplWorker))
                             : new ManagerMainForm(new RequestsToServerHandlerForManager(m_Stream, loginEventArgs.LoginType as ApplManager));
            m_BaseForm.ShowDialog();
        }

        private void handleLogin()
        {
            m_LoginForm = new LoginForm(m_Stream);
            m_LoginForm.LoginSuccessful += new LoginSuccessfulHandler(createUI);
            m_LoginForm.ShowDialog();
        }

        private void createConnetionToServer()
        {
            m_ServerEndPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 450);
            m_TCPClient.Connect(m_ServerEndPoint);
            m_Stream = m_TCPClient.GetStream();
            //"127.0.0.1"
            //192.168.1.101
        }  
    }

}
